<template>
<div>
  <el-row>
    <el-col :span="18" :offset="3">
      <div class="demo-input-size">
        <el-col :span="3">
          <el-input size="medium" @keyup.enter="sel()" v-model="name" placeholder="用户名"></el-input>
        </el-col>
        <el-col :span="3" :offset="1">
          <el-input size="medium" @keyup.enter="sel()" v-model="email" placeholder="邮箱"></el-input>
        </el-col>
        <el-col :span="3" :offset="1">
          <el-input size="medium" @keyup.enter="sel()" v-model="mobile" placeholder="电话"></el-input>
        </el-col>
        <el-col :span="2" :offset="1">
          <el-button @click="sel" :disabled="perms.indexOf('sys:user:add') === -1" type="primary">搜索</el-button>
        </el-col>
        <el-col :span="2" :offset="1">
          <el-button @click="reset" :disabled="perms.indexOf('sys:user:delete') === -1" type="danger">重置</el-button>
        </el-col>
        <el-col :span="2" :offset="1">
          <el-button @click="add" :disabled="perms.indexOf('sys:user:edit') === -1" type="success">添加</el-button>
        </el-col> 
      </div>
      <el-table
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column
          fixed
          prop="id"
          label="ID">
        </el-table-column>
        <el-table-column
          prop="name"
          label="姓名">
        </el-table-column>
        <el-table-column
          prop="dept.name"
          label="部门名称">
        </el-table-column>
        <el-table-column
          label="角色">
          <template slot-scope="scope">
            <span v-for="r,idx in scope.row.roles" :key="idx">
              {{r.name}}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话">
        </el-table-column>
        <el-table-column
          label="状态">
          <template slot-scope="scope">
            <el-switch
            @change="changeStatus(scope.row.status,scope.row.id,scope.row.name)"
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949">
            </el-switch>
          </template>  
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="180">
          <template slot-scope="scope">
            <el-button
              size="mini"
              icon="el-icon-edit"
              @click="edit(scope.row.id)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="del(scope.row.id,scope.row.name)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  <!-- @current-change页码改变的时候会触发的事件,会自动传递页码 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        @current-change="getUsers"
        >
      </el-pagination>
    </el-col>
    <edit-user ref="xx" :current="current" @refresh="getUsers"></edit-user>
    <add-user ref="yy" @refresh="getUsers"></add-user>
  </el-row>
</div>
</template>

<script>
import AddUser from './AddUser.vue'
import EditUser from './EditUser.vue'
export default {
  components: { EditUser, AddUser },
  data() {
    return {
      tableData : [],
      total : 0,
      pageSize : 5,
      current : 1,
      name:'',
      email:'',
      mobile:'',
      perms: [],
      status : false
    }
  },
  mounted() {
    this.perms = this.$route.meta.perms
    this.getUsers()
  },
  methods: {
    getUsers(page = 1){
      this.$http.get(`/user/${page}/${this.pageSize}`).then(res => {
        this.tableData = res.data.data.data
        this.total = res.data.data.total
        this.pageSize = res.data.data.pageSize
        this.current = res.data.data.current
      })
    },
    sel(){
      this.$http({
        method : "get",
        url : `/user`,
        params : {
          name:this.name,
          email:this.email,
          mobile:this.mobile,
          pageSize:this.pageSize
        }
      }).then(res =>{
        this.tableData = res.data.data.data
        this.total = res.data.data.total
        this.pageSize = res.data.data.pageSize
        this.current = res.data.data.current
      })
    },
    reset(){
      this.name ='',
      this.email='',
      this.mobile='',
      this.getUsers()
    },
    async add() {
      const res = await this.$http.get('/role')
      this.$refs.yy.$data.roles = res.data.data
      const res2 = await this.$http.get('/dept')
      this.$refs.yy.$data.depts = this.formatData(res2.data.data)
      this.$refs.yy.$data.iseditUserDialog2 = true
    },
    async del(id,name) {
      try {
        await this.$confirm(`确认要删除${name}吗?`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const res = await this.$http.delete(`/user/${id}`)
        if(res.data.code == 0){
          this.$message({
              type: 'success',
              message: '删除成功!'
          });
          this.getUsers(this.current)
        }
      } catch (err) {
        this.$message({
            type: 'info',
            message: '已取消删除'
          });  
      }
    },
    async edit(id) {
      try {
        const r = await this.$http.get(`/user/${id}`)
        this.$refs.xx.$data.user = r.data.data
        this.$refs.xx.$data.deptId = r.data.data.deptId
        let arr = []
        for(let i = 0; i<r.data.data.roles.length;i++){
            arr.push(r.data.data.roles[i].id)
        }
        this.$refs.xx.$data.roleList = arr
        const res = await this.$http.get('/role')
        this.$refs.xx.$data.roles = res.data.data
        const res2 = await this.$http.get('/dept')
        this.$refs.xx.$data.depts = this.formatData(res2.data.data)
        this.$refs.xx.$data.iseditUserDialog = true
      } catch (error) {
        console.log(error);
      }
    },
    changeStatus(status,id,name){
      let str =``
      if(status){
        str += `启用`
      }else{
        str += `停用`
      }
      this.$confirm(`是否${str}${name}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.put(`/user/${status}/${id}`).then(res => {
          if(res.data.code ==0){
              this.$message({
              type: 'success',
              message: `${str}成功!`
            });
            return;
          }
          this.$message({
            type: 'info',
            message: `${str}失败`
          });
          })  
        }).catch(() => {
          this.$message({
            type: 'info',
            message: `已取消${str}`
          });          
        });
    },
    formatData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.formatData(data[i].children)
        }
      }
      return data;
    }
  }
}
</script>

<style>

</style>